package com.flute.tools.xml;

import org.jdom.Attribute;
import org.jdom.Element;

import com.flute.tools.util.StringUtil;

public class XmlNode implements IXmlNode {
	private Element element;

	public XmlNode(String name) {
		this.element = new Element(name);
	}

	public void setText(String text) {
		this.element.setText(text);
	}

	public void addChild(XmlNode node) {
		this.element.addContent(node.element);
	}

	public void addAttribute(String name, String value) {
		this.element.setAttribute(name, value);
	}

	@Override
	public String toXml() {
		return getElementString(element);
	}

	private String getElementString(Element element) {
		String xml = START_LEFT_ANGLE;
		xml = xml + element.getName();

		for (Object content : element.getAttributes()) {
			Attribute at = (Attribute) content;
			xml = xml + new AttributeXmlNode(at).toXml();
		}

		xml = xml + RIGHT_ANGLE;

		if (!StringUtil.isNullOrEmpty(element.getText())) {
			xml = xml + DATA_START + element.getText() + DATA_END;
		}

		for (Object obj : element.getChildren()) {
			xml = xml + getElementString(((Element) obj));
		}

		xml = xml + END_LEFT_ANGLE + element.getName() + RIGHT_ANGLE;

		return xml;
	}
}
